#INVENTORY MODELS
from django.db import models

class equipmentManager(models.Manager):
	def slotsUsed(self, ind):
		"""returns all the slots in use for an individual"""
		return self.filter(individual = ind)
	
	def slotAvailable(self, ind, itemSlot):
		"""
		returns true if the individual has the given slot free for
		an item to be equiped
		"""
		slots = self.slotsUsed(ind).filter(slot=itemSlot)
		if slots.count() < itemSlot.slotsPerTrait:
			return True
		return False
	
	def hasItemReqs(self, ind, itmInst):
		"""
		returns true if the individual has the necessary skills/traits/
		etc to equip the item
		"""
		if itmInst.size != ind.size:
			return False
		return True
	
	def equipItem(self, ind, itmInst):
		"""
		Equips the individual with the given item instance
		"""
		try:
			slot = itmInst.item.itemType.slotUsed
			if self.hasItemReqs(ind, itmInst) and \
		   	   self.slotAvailable(ind, slot):
				   #The reqirements are met and the slot is free
		   	       self.create(individual= ind, item = itmInst, slot= slot)
		   	       return True
		   	else:
		   		return False
		except Exception,e:
			return False
	
	def unEquipItem(self, ind, itmInst):
		"""
		unEquips the item from an individual
		"""
		try:
			x = self.get(individual = ind, item = itmInst)
			x.delete()
			return True
		except:
			return False
			
	def allItems(self, ind):
		""" 
		Returns a list of all items an individual has equiped
		"""
		try:
			x = self.filter(individual = ind)
			return x
		except:
			return False
				
class itemInstance(models.Model):
	"""
	Instances of items that belong to a player
	"""
	user = models.ForeignKey('auth.user', default = 1)
	item = models.ForeignKey('items.item')
	size = models.ForeignKey('attributes.size', null = True)
	material=models.ForeignKey('items.material')
	
	def getDefence(self, dt):
		#gets the combined defence of the armor and material
		baseDef = self.item.armor.getDefence(dt)
		mat = self.material.getDefence(dt)
		return baseDef+mat
	
	def getAttack(self):
		baseDam = self.item.weapon.damage
		baseDam.size = self.size
		baseDam.power += self.material.getAttack(baseDam.damageType)
		return baseDam
	def __unicode__(self):
		return "%s owned by %s"%(self.item, self.user)
	
class itemSlot(models.Model):
	name = models.CharField(max_length = 20, unique = True)
	traitRequired = models.ForeignKey('attributes.trait')
	slotsPerTrait = models.IntegerField(default =1)
	#Some traits, such as arms, can have multiple items equiped, 1 per arm
	
	def __unicode__(self):
		return self.name
	
	
class equipedItems(models.Model):
	"""
	Each entry represents an item that a monster has equiped
	"""
	individual = models.ForeignKey('monster.individual', db_index=True)
	item = models.ForeignKey('itemInstance', unique = True)
	slot = models.ForeignKey('itemSlot')
	objects = equipmentManager()
	
	def __unicode__(self):
		return "%s with %s on %s"%(self.individual.name, self.item.item.name, self.slot.name)
